package com.fire.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.util.HttpURLConnection;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Aspire
 * @date 2018-04-18
 */
public class HttpUtils {
	private final static Logger log = Logger.getLogger(HttpUtils.class);
	private static final String HTTPS = "https";
	public static String request(String in, String httpUrl, int timeout)throws Exception {
		PostMethod postmethod = new PostMethod(httpUrl);
		URL url = new URL(httpUrl);
		if(url.getProtocol().equals(HTTPS)){
            Protocol https = new Protocol(HTTPS, new SslProtocolSocketFactory(), url.getPort()==-1?443:url.getPort());
            Protocol.registerProtocol(HTTPS, https);
        }
		String responseBodyAsString = "";
		try {
			postmethod.setRequestBody(in);
			postmethod.setRequestHeader("Content-type", "application/json;charset=UTF-8");
			
			System.out.println("请求服务开始...");
			System.out.println("转发bia-middle服务URL=" + url);
			
			// 指定请求内容的类型
			HttpClient httpclient = new HttpClient();
			HttpClientParams httparams = new HttpClientParams();
			// int timeout = 0;
			if (timeout <= 0) {
				timeout = 10* 1000;
			}
			httparams.setSoTimeout(timeout);
			httpclient.setParams(httparams);
			int result = httpclient.executeMethod(postmethod);
			System.out.println("转发服务结束,返回结果代码=" + result);
			byte[] cont = postmethod.getResponseBody();
			String re = new String(cont, "UTF-8");
			postmethod.releaseConnection();
			postmethod = null;
			responseBodyAsString = re;
		}catch (Exception e) {
			throw e;
		} finally {
			if (postmethod != null) {
				try {
					postmethod.releaseConnection();
					postmethod = null;
				} catch (Exception e1) {
					
				}
			}
		}
		return responseBodyAsString;

	}

	public static AjaxResult toPost(String url,Object obj) throws Exception{
		AjaxResult ajaxResult = new AjaxResult();

		Field[] fields = obj.getClass().getDeclaredFields();

		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		CloseableHttpResponse response = null;
		final List<NameValuePair> values = new ArrayList<NameValuePair>();
		try {
			for (int i = 1; i < fields.length; i++) {
				Field field = fields[i];
				field.setAccessible(true);
				if(null != field.get(obj)){
					if (field.getType().toString().contains("List")) {
						log.debug("doPost()-->请求参数:"+field.getName()+"----------请求参数值："+ JSONObject.toJSONString((List)field.get(obj)));
						values.add(new BasicNameValuePair(field.getName(), JSONObject.toJSONString((List)field.get(obj))));
					}else {
						log.debug("doPost()-->请求参数:"+field.getName()+"----------请求参数值："+String.valueOf(field.get(obj)));
						values.add(new BasicNameValuePair(field.getName(),String.valueOf(field.get(obj))));
					}
				}
			}
			//进行转码
			httppost.setEntity(new UrlEncodedFormEntity(values, HTTP.UTF_8));
			//httppost.addHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
			log.info("doPost()-->param:"+values);
			log.debug("doPost()-->call url <"+ url +"> start");
			log.info("doPost()-->call url <"+ url +"> start");
			response = httpclient.execute(httppost);
			log.debug("doPost()-->call url <"+ url +"> end");
			log.info("doPost()-->call url <"+ url +"> end");
			int code = response.getStatusLine().getStatusCode();
			log.debug("doPost()-->http resposeCode is:" + code);
			log.info("doPost()-->http resposeCode is:" + code);

			if (HttpURLConnection.HTTP_OK == code) {
				String resEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
				log.debug("doPost()-->resEntity is:" + resEntity);
				log.info("doPost()-->resEntity is:" + resEntity);
				JSONObject jSonObject_first = JSON.parseObject(resEntity);
				ajaxResult = JSONObject.toJavaObject(jSonObject_first, AjaxResult.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}  finally {
			if(response != null) {
				response.close();
				log.debug("doPost()-->end");
			}
		}
		return ajaxResult;
	}

	
	/**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url,String json){
        
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        String response = null;
        try {
            //StringEntity s = new StringEntity(json.toString());
            StringEntity s;
            s = new StringEntity(json,"UTF-8");
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            	response = EntityUtils.toString(res.getEntity());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
}
